package com.example.analyzejson;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getCanonicalName();
    private Button btnAnalyzeJSON1,btnAnalyzeJSON2,btnAnalyzeJSON3,btnAnalyzeJSONArray1,btnAnalyzeJSONArray2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnAnalyzeJSON1 = findViewById(R.id.analyzeJSON1);
        btnAnalyzeJSON2 = findViewById(R.id.analyzeJSON2);
        btnAnalyzeJSON3 = findViewById(R.id.analyzeJSON3);
        btnAnalyzeJSONArray1 = findViewById(R.id.analyzeJSONArray1);
        btnAnalyzeJSONArray2 = findViewById(R.id.analyzeJSONArray2);
        analyzeJSON1(btnAnalyzeJSON1);
        analyzeJSON2(btnAnalyzeJSON2);
        analyzeJSON3(btnAnalyzeJSON3);
        analyzeJSONArray1(btnAnalyzeJSONArray1);
        analyzeJSONArray2(btnAnalyzeJSONArray2);
    }

    /**
     * 解析JSON对象
     * {
     * "name":"李四",
     * "age":99,
     * "hobby":"爱好是练习截拳道"
     * }
     *
     * @param view
     */
    public void analyzeJSON1(View view) {
        String data = readJsonFromAssets("pottingJSON1.json");
//        Log.d(TAG, "result: " + data);
        try {
            JSONObject jsonObject = new JSONObject(data);
            /**
             * 为什么要使用jsonObject.optString， 不使用jsonObject.getString
             * 因为jsonObject.optString获取null不会报错
             */
            String name = jsonObject.optString("name", null);
            int age = jsonObject.optInt("age", 0);
            String hobby = jsonObject.optString("hobby", null);
            Log.d(TAG, "analyzeJSON1的解析结果: name: " + name + "age: " + age + "hobby: " + hobby);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析JSON对象-带Key
     * {
     *     "student":{
     *         "name":"李四",
     *         "age":99,
     *         "hobby":"爱好是练习截拳道"
     *     }
     * }
     * @param view
     */
    public void analyzeJSON2(View view) {
        String data = readJsonFromAssets("pottingJSON2.json");
        try {
            JSONObject jsonObjectAll = new JSONObject(data);
            String student = jsonObjectAll.optString("student", null);
            if (!TextUtils.isEmpty(student)) {
                JSONObject jsonObject = new JSONObject(student);
                String name = jsonObject.optString("name", null);
                int age = jsonObject.optInt("age", 0);
                String hobby = jsonObject.optString("hobby", null);
                Log.d(TAG, "analyzeJSON2的解析结果 -> name: " + name + ", age: " + age + ", hobby: " + hobby);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析JSON对象-嵌套对象
     * {
     *     "student":{
     *         "name":"李四",
     *         "age":99,
     *         "hobby":"爱好是练习截拳道",
     *         "dog":{
     *             "name":"阿黄",
     *             "age":77,
     *             "sex":"母"
     *         }
     *     }
     * }
     * @param view
     */
    public void analyzeJSON3(View view){
        String data = readJsonFromAssets("pottingJSON3.json");
        try {
            JSONObject jsonObjectAll = new JSONObject(data);
            String student = jsonObjectAll.optString("student",null);
            if (!TextUtils.isEmpty(student)){
                JSONObject jsonObject = new JSONObject(student);
                String name = jsonObject.optString("name",null);
                int age = jsonObject.optInt("age",0);
                String hobby = jsonObject.optString("hobby",null);
                // 解析dogJSON对象
                String dogStr = jsonObject.optString("dog",null);
                // 定义dog的JSON对象
                JSONObject dogJSONObject = new JSONObject(dogStr);
                String dogName = dogJSONObject.optString("name",null);
                int dogAge = dogJSONObject.optInt("age",0);
                String dogSex = dogJSONObject.optString("sex",null);

                Log.d(TAG,"analyzeJSON3的解析结果 -> name: "+name+", age: "+age+", hobby: "+hobby+"\n"+"dogName: "+dogName+", dogAge: "+ dogAge+", dogSex: "+dogSex);

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 解析JSON数组
     * [
     *     {
     *         "name":"君君",
     *         "age":89,
     *         "sex":"男"
     *     },
     *     {
     *         "name":"小君",
     *         "age":99,
     *         "sex":"女"
     *     },
     *     {
     *         "name":"大君",
     *         "age":88,
     *         "sex":"男"
     *     }
     * ]
     * @param view
     */
    public void analyzeJSONArray1(View view){
        String data = readJsonFromAssets("pottingJSONArray1.json");
        try {
            JSONArray jsonArray = new JSONArray(data);
            for (int i = 0; i < jsonArray.length(); i++) {
                // JSON数组里具体的JSON对象
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String name = jsonObject.optString("name",null);
                int age = jsonObject.optInt("age",0);
                String sex = jsonObject.optString("sex",null);
                Log.d(TAG,"analyzeJSONArray1的解析结果 -> name: "+name+", age: "+age+", sex: "+sex);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析JSON数组-带Key
     * {
     *     "person":[
     *         {
     *             "name":"一一",
     *             "age":89,
     *             "sex":"男"
     *         },
     *         {
     *             "name":"小君",
     *             "age":99,
     *             "sex":"女"
     *         },
     *         {
     *             "name":"大君",
     *             "age":88,
     *             "sex":"男"
     *         }
     *     ]
     * }
     * @param view
     */
    public void analyzeJSONArray2(View view){
        String data = readJsonFromAssets("pottingJSONArray2.json");
        try {
            /**
             * JSON数组再牛逼，一旦有了 key person 这样的标记，就必须先是个 JSON对象
             * 最外层的JSON对象，最大的哪个 { ... }
             */
            JSONObject jsonObjectAll = new JSONObject(data);
            // 通过标识(person)，获取JSON数组
            JSONArray jsonArray = jsonObjectAll.getJSONArray("person");
            for (int i = 0; i < jsonArray.length(); i++) {
                // JSON数组里面的具体-JSON对象
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String name = jsonObject.optString("name",null);
                int age = jsonObject.optInt("age",0);
                String sex = jsonObject.optString("sex",null);
                Log.d(TAG,"analyzeJSONArray2的解析结果 -> name: "+name+", age: "+age+", sex: "+sex);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从assets中读取文件
     * @param fileName
     * @return
     */
    private String readJsonFromAssets(String fileName) {
        StringBuilder jsonData = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader buffReader = null;
        InputStreamReader inputStreamReader = null;
        try {
            inputStream = getAssets().open(fileName);
            inputStreamReader =
                    new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            buffReader = new BufferedReader(inputStreamReader);
            int temp = 0;
            //当temp等于-1时，表示已经到了文件结尾，停止读取
            while ((temp = buffReader.read()) != -1) {
                jsonData.append((char) temp);
            }
            inputStreamReader.close();
            buffReader.close();
            inputStream.close();
        } catch (IOException exception) {
            exception.printStackTrace();
        }
        return jsonData.toString();
    }

    /**
     * 读取/data/data/com.example.analyzejson/files/下的JSON文件
     * @param fileName
     * @return
     */
    private String readFile(String fileName) {
        String result = null;
        try {
            InputStream inputStream = openFileInput(fileName);

            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            result = new String(bytes);

            inputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}